package br.ufmg.ubicomp.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.style.UpdateLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import br.ufmg.ubicomp.droidguide.common.DroidGuideConfigurationManager;
import br.ufmg.ubicomp.droidguide.common.EntityProperties;
import br.ufmg.ubicomp.droidguide.communication.CommNotificationListener;
import br.ufmg.ubicomp.droidguide.communication.CommunicationManager;
import br.ufmg.ubicomp.droidguide.communication.DGCommManagerOperation;
import br.ufmg.ubicomp.droidguide.communication.DroidServiceParamCommService;
import br.ufmg.ubicomp.droidguide.eventservice.DroidGuideRemoteService;
import br.ufmg.ubicomp.droidguide.eventservice.DroidGuideServiceParameter;
import br.ufmg.ubicomp.droidguide.eventservice.enums.ParameterType;

public class ServiceParamList extends Activity implements TextWatcher, CommNotificationListener {
	
	private TextView paramName, serviceTitle, info;
	private EditText paramValue;
	private ImageButton previous, next;
	private DroidGuideRemoteService service = null; 
	private List<DroidGuideServiceParameter> parameters = new ArrayList<DroidGuideServiceParameter>();
	private DroidGuideServiceParameter param = null;
	private int index = 0;
	String serviceKey = "agpkcm9pZGd1aWRlcg0LEgdTZXJ2aWNlGAEM";
	String droidGuideUserKey = "agpkcm9pZGd1aWRlchQLEg5Ecm9pZEd1aWRlVXNlchgGDA";
	String serviceParameterKey = "agpkcm9pZGd1aWRlchYLEhBTZXJ2aWNlUGFyYW1ldGVyGAIM";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initializeUIElements();
        
        //loadServicesOnUILocal();
        
        loadServicesOnUI();
    }

	private void loadServicesOnUILocal() {
		
		service = new DroidGuideRemoteService();
		service.setDescription("Flight Service");
		service.setKey("01");
		service.setKind("DroidGuideRemoteService");
		service.setMarked(true);
		service.setState("ACTIVE");
		service.addParameter("flightNumber", "3200", ParameterType.REQUEST);
		service.addParameter("airport", "plu", ParameterType.REQUEST);
		parameters = new ArrayList<DroidGuideServiceParameter>(service.getParameters());
		if (!parameters.isEmpty())
		{
			index = 0;
			previous.setEnabled(false);
	        loadCurrentParameter();
			
		}
	}

	private void loadServicesOnUI() {
		loadService();
		parameters = new ArrayList<DroidGuideServiceParameter>();
		
		serviceTitle.setText(service.getDescription());
		
        parameters.addAll(service.getRequestParameters());
        param = parameters.get(index);
        while (!param.getType().equals(ParameterType.REQUEST) && index < parameters.size())
        {	
        	index++;
            param = parameters.get(index);
        }
        loadCurrentParameter();
	}

	private void loadCurrentParameter() {
		param = parameters.get(index);
		paramName.setText(param.getName());
        paramValue.setText(param.getValue());
        info.setText("Parameter " + (index + 1) + " of " + parameters.size());
	}

	private void initializeUIElements() {
		serviceTitle = (TextView) findViewById(R.id.title);

		info = (TextView) findViewById(R.id.info);
		
		paramName = (TextView) findViewById(R.id.name);
		
        paramValue = (EditText) findViewById(R.id.value);
        paramValue.addTextChangedListener(this);
        
        NavigationClick navClick = new NavigationClick();
        previous = (ImageButton) findViewById(R.id.previous);
        previous.setOnClickListener(navClick);
        previous.setImageResource(R.drawable.previous);
        
        next = (ImageButton) findViewById(R.id.next);
        next.setOnClickListener(navClick);
        next.setImageResource(R.drawable.next);
        
	}

	@Override
    public boolean onOptionsItemSelected(MenuItem item){
    	Intent i;
    	
    	if (item.getItemId() == 0) // ok
    	{
    		Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_SHORT).show();
    		try {
    			int paramsSaved = saveServiceParams1();
    			Toast.makeText(getApplicationContext(), paramsSaved + 
    					" params saved.", Toast.LENGTH_SHORT).show();
    			//saveServiceParams2();

			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
			}
    	} else if (item.getItemId() == 1)  // cancel
    	{
    		Toast.makeText(getApplicationContext(), "cancel", Toast.LENGTH_SHORT).show();
    	}
        return true;
    }

	private void saveServiceParams2() throws Exception {
		CommunicationManager manager = new CommunicationManager();
		Map<String, String> params = new HashMap<String, String>();
		for (DroidGuideServiceParameter param: parameters)
		{
			params.put("key", param.getValueKey());
			params.put("value", param.getValue());
			manager.execute(
				DGCommManagerOperation.SAVE_SERVICE_PARAM_VALUE, 
				params, this);
		}
	}

	private int saveServiceParams1() throws Exception {
		int paramsSaved = 0;
		for (DroidGuideServiceParameter param: parameters)
		{
			String key = param.getValueKey();  
			String value = param.getValue();
			DroidServiceParamCommService commServ = new DroidServiceParamCommService();
			commServ.saveServiceParamValue(key, value);
			paramsSaved++;
		}
		Toast.makeText(getApplicationContext(), 
			"Parameters saved successfully["+paramsSaved+"]", 
				Toast.LENGTH_SHORT).show();
		return paramsSaved;
	}
	
	
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0,0, 0, "Ok").setIcon(R.drawable.ic_ok)
		 .setIntent(new Intent("OK"));
        menu.add(0,1, 0, "Cancel").setIcon(R.drawable.ic_cancel)
		 .setIntent(new Intent("CANCEL"));
      return true;
    }
	
	private void loadService(){
		try {
			DroidGuideConfigurationManager.getInstance().addData("server", "http://10.0.2.2:8080/"); 
					//"http://localhost:8080/");
			DroidGuideConfigurationManager.getInstance().addData("httpApi", "JAVA_NET");
			
			DroidServiceParamCommService commServ = new DroidServiceParamCommService();
			service = commServ.getService(serviceKey, droidGuideUserKey);
			
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}
	
	private class NavigationClick implements Button.OnClickListener {
		@Override
		public void onClick(View arg0) {
			String msg = null;
			param.setValue(paramValue.getText().toString());
			if (arg0.getId() == R.id.previous){
				msg = "previous";
				if (index > 0){
					index--;
				}
			} else {
				msg = "next";
				if (index < parameters.size()-1){
					index++;
				}
			}
			Toast.makeText(getApplicationContext(), msg + " - " + index, Toast.LENGTH_SHORT).show();
			previous.setEnabled(index > 0);
			next.setEnabled(index < parameters.size() - 1);
			loadCurrentParameter();
		}	
	}

	@Override
	public void afterTextChanged(Editable arg0) {
//		Toast.makeText(getApplicationContext(), "afterTextChanged", Toast.LENGTH_SHORT).show();
		param.setValue(paramValue.getText().toString());
		
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
	}

	public void notifyIncommingMessage(DGCommManagerOperation operation, Object returnValue) {
		
		switch (operation)
		{
		case SAVE_SERVICE_PARAM_VALUE:
			EntityProperties entity = (EntityProperties) returnValue;
			Log.i("notifyIncommingMessage", "object saved successfully");
			//Toast.makeText(getApplicationContext(), "object saved successfully", Toast.LENGTH_SHORT).show();
			break;
		}
		finish();				
	}
}